<?php
/**
 * JSONRPCProxy class definition
 *   
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MutantVole
 */

/**
 * Implements a proxy for calling JSON-RPC services
 * @package MutantVole
 * @subpackage JSONRPC
 */ 
class JSONRPCProxy {
    /**
     * Constructor
     * @param string $endpoint
     */
	public function __construct($endpoint) {
		$this->endpoint = $endpoint;
		$this->smd = JSONRPC::Request($this->endpoint .'/system.description', 'system.description', null, true);
		$this->ParseSMD();
	}
	
	/**
	 * Overloaded __call. Calls registered JSON-RPC methods
	 * @param string $name
	 * @param mixed $args
	 * @return mixed
	 */
	public function __call($name, $args) {
		if (in_array($name, $this->methods)) {
			return JSONRPC::Request($this->endpoint .'/'. $name, $name, $args[0]);
		} else {
			return false;
		}
	}
	
	/**
	 * Get a list of registered methods
	 * @return array
	 */
	public function AvailableMethods() {
		return $this->methods;
	}
	
	/**
	 * Get the parameters for a method
	 * @param string $method
	 * @return array
	 */
	public function DescribeMethod($method) {
		if (in_array($method, $this->methods)) {
			return $this->descriptions[$method];
		} else {
		    return false;
		}
	}
	
	/**
	 * Parse the SMD response and register defined methods in the proxy
	 */
	private function ParseSMD() {
		if (is_array($this->smd->methods)) {
			foreach ($this->smd->methods as $method) {
				$this->methods[] = $method->name;
				
				if (is_array($method->parameters)) {
					foreach ($method->parameters as $param)
					$this->descriptions[$method->name][] = $param->name;
				}
			}
		}
	}
	
	/**
	 * URL endpoint for the JSON-RPC service
	 * @var string
	 */
	protected $endpoint;
	
	/**
	 * List of methods available
	 * @var array
	 */
	protected $methods;
	
	/**
	 * List of method parameters
	 * @var array
	 */
	protected $descriptions;
	
	/**
	 * SMD response from the JSON-RPC endpoint
	 * @var mixed
	 */
	protected $smd;
}
?>